package gw.com.android.presenter;

import android.app.Activity;
import android.os.Bundle;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import org.json.JSONException;
import org.json.JSONObject;

import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.presenter.http.AccountRequest;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.terminal.GTSDataListener;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.dialog.AddAccountInfoDialog;
import gw.com.android.ui.dialog.BackLoginDialog;
import gw.com.android.ui.dialog.BindEnterPasswordDialog;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.android.ui.dialog.SwitchAccountDialog;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.app.Logger;
import www.com.library.interfaces.ReqCallBack;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.util.NetworkMonitor;
import www.com.library.util.StringUtils;
import www.com.library.view.BtnClickListener;

/**
 * Created by jay on 2017/7/11.
 */

public class SwitchAccountPresenter {

    private LoginPresenter mPresenter = null;
    private int mSeq = 0;
    private DataItemDetail mAccountInfo;
    public Activity mContext;

    private String loginAccount = "";
    private String loginPass = "";
    private int mAccountType = 0;
    private String switchFrom = "";
    private PresenterImpl mPresenterImpl = null;
    private Disposable rxBusRegister;

    public SwitchAccountPresenter(Activity activity, PresenterImpl impl) {
        init();
        mContext = activity;
        mPresenterImpl = impl;
    }

    private void init() {
        mPresenter = new LoginPresenter(mContext);
        if ("".equals(GTConfig.instance().mCurName)) {
            mAccountInfo = DataManager.instance().mAccount;
            GTConfig.instance().mCurName = mAccountInfo.getString(GTSConst.JSON_KEY_NAME);
        }
        rxBusRegister = RxBus.getInstance().register(GTSConst.REPLY_TYPE_GET_CUSTOMER, Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        onResultPresenter(bundle);
                    }
                });
        AppTerminal.instance().getMobileNumber();//从配置中心拿手机号
    }

    protected void onResultPresenter(Bundle bundle) {
        if (null != bundle) {
            int iValue = bundle.getInt("iValue");
            if (iValue == 0 && mSeq == bundle.getInt("iNotification")) {
                String rgsUrl = bundle.getString("strObject");
                if (!StringUtils.isEmpty(rgsUrl)) {
                    try {
                        JSONObject jsonRgsUrl = new JSONObject(rgsUrl);
                        String curName = GTConfig.instance().mCurName;
                        if (!jsonRgsUrl.isNull("demoCustomerNumber") && !curName.equals(jsonRgsUrl.getString("demoCustomerNumber"))) {
                            hideLoading();
                            String error = AppMain.getAppString(R.string.account_isbinded);
                            BackLoginDialog.showBackLoginDialog(mContext, error);
                        } else {
                            AccSwitch(mAccountType);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        hideLoading();
                    }
                } else {
                    AccSwitch(mAccountType);
                }
            } else if (iValue == 1326) {
                onPhoneRequestFail(7);//账户被锁定
            } else {
                onPhoneRequestFail(iValue);
            }
            if (null != rxBusRegister && !rxBusRegister.isDisposed()) {
                rxBusRegister.dispose();
                rxBusRegister = null;
            }
        }
    }

    public void AccSwitch(int accountType) {
        if (!"".equals(GTConfig.instance().mCurLoginPhone)) {
            String loginPhoneNo = GTConfig.instance().mCurLoginPhone;
            String loginPass = GTConfig.instance().mUserPwd;
            mSeq = GTSDataListener.curSeq++;
            accPhoneLoginFun(mSeq, loginPhoneNo, loginPass, accountType);
        } else {
            //获取交易服务器手机号
            mAccountInfo = DataManager.instance().mAccount;
            String loginPhoneNo = mAccountInfo.getString(GTSConst.JSON_KEY_PHONE);
            if (!StringUtils.isEmpty(loginPhoneNo)) {
                if (loginPhoneNo.startsWith("86")) {
                    loginPhoneNo = loginPhoneNo.substring(2, loginPhoneNo.length());
                }
                String loginPass = GTConfig.instance().mUserPwd;
                mSeq = GTSDataListener.curSeq++;
                accPhoneLoginFun(mSeq, loginPhoneNo, loginPass, accountType);
            } else {
                Logger.i("切换账号没获取到手机号！！！");
                hideLoading();
//                GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_REAL);
                ActivityManager.backLogin(mContext, false);
            }
        }
    }

    /**
     * 向配置中心取得账户相关的关联信息
     */
    public void AccGetrelatedCustomer() {
        mSeq = GTSDataListener.curSeq++;
        GTSDataListener.instance().addSeqList(mSeq + "", AppContances.NORMALREQ_TYPE_GET_RELATEDCUSTOMER);
        AppTerminal.instance().NormalReqConfigSvr(ConfigType.HTTP_GET_RELATEDCUSTOMER_TAG, "", mSeq);
    }

    /**
     * 切换账户逻辑
     */
    public void AccAccountSwitch(int accountType, String loginfrom) {
        showLoading();
        mAccountType = accountType;
        switchFrom = loginfrom;
        if (accountType == GTConfig.ACC_TYPE_DEMO) {
            AccSwitch(accountType);
        } else {
            //通过取的登录配置中心的数据判断该登录的模拟账号关联的手机号是否已经绑定过其他账号
            AccGetrelatedCustomer();
        }

    }

    /**
     * getCustomerByMobileNoAndPassword 接口
     */
    private void accPhoneLoginFun(int mSeq, String mCurName, String mPassword, final int accountType) {
        PhoneLoginPresenter.instance().PhoneLoginFun(AppContances.NORMALREQ_TYPE_GET_CUSTOMERBYMOBILE, mSeq, mCurName, mPassword,
                new PhoneLoginPresenter.OnMobileReqResultListener() {
                    @Override
                    public void reqResultSuccess(Object mObject) {
                        JSONObject result = (JSONObject) mObject;
                        accLoginOrBind(result.toString(), accountType);
                    }

                    @Override
                    public void reqResultFail(int failCode) {
                        onPhoneRequestFail(failCode);
                    }
                });
    }

    /**
     * bindCustomer 接口
     */
    private void accBindCustomer(final String loginAccount, DataItemDetail item, final String mPassWord, final int accountType, final int loginType) {
        if (!NetworkMonitor.hasNetWork()) {
            return;
        }
        final String bindName = item.getString("customerNumber");
        mSeq = GTSDataListener.curSeq++;

        PhoneLoginPresenter.instance().BindCustomerFun(AppContances.NORMALREQ_TYPE_BINDCUSTOMER, mSeq, accountType, bindName, mPassWord, new PhoneLoginPresenter.OnMobileReqResultListener() {
            @Override
            public void reqResultSuccess(Object mObject) {
                BindEnterPasswordDialog.instance().dismiss();
                //更新账户密码，更新模拟密码
                GTConfig.instance().updateLoginInfo(GTConfig.instance().mCurName, mPassWord, accountType);
                if (accountType == GTConfig.ACC_TYPE_REAL) {//切换到真实，真实绑定成功，这时需要判断模拟是否已经绑定，若没有，则需要再绑定模拟，并更新密码
                    JSONObject result = (JSONObject) mObject;
                    if (!result.isNull("result")) {
                        try {
                            JSONObject resultObj = result.getJSONObject("result");
                            if (!resultObj.isNull("customerNumber") && resultObj.isNull("demoCustomerNumber")) {//绑定模拟并登录真实
                                accBindDemoCustomer(GTConfig.instance().mCurName, mPassWord, loginAccount, loginType, GTConfig.ACC_TYPE_DEMO);
                            } else {
                                //执行登录
                                accAccountLogin(loginAccount, mPassWord, loginType);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                } else {
                    //执行登录
                    accAccountLogin(loginAccount, mPassWord, loginType);
                }
            }

            @Override
            public void reqResultFail(int failCode) {
                hideLoading();
                if (failCode == 1) {
                    BindEnterPasswordDialog.instance().setmErrorViewVisble(true);
                } else {
                    BindEnterPasswordDialog.instance().dismiss();
                    onPhoneRequestFail(failCode);
                }
            }
        });
    }

    private void accBindDemoCustomer(final String bindName, final String mPassWord, final String loginAccount, final int loginType, final int bindType) {
        mSeq = GTSDataListener.curSeq++;
        PhoneLoginPresenter.instance().BindCustomerFun(AppContances.NORMALREQ_TYPE_BINDCUSTOMER, mSeq, bindType, bindName, mPassWord, new PhoneLoginPresenter.OnMobileReqResultListener() {

            @Override
            public void reqResultSuccess(Object mObject) {
                //更新账户密码，更新模拟密码
                GTConfig.instance().updateLoginInfo(bindName, mPassWord, bindType);
                //执行登录
                accAccountLogin(loginAccount, mPassWord, loginType);
            }

            @Override
            public void reqResultFail(int failCode) {
                onPhoneRequestFail(failCode);
            }
        });
    }

    /**
     * 開立模擬賬戶 接口
     */
    private void openDemoAccount(JSONObject jsonResult) {
        try {
            JSONObject resultObj = jsonResult.getJSONObject("result");
            String uuid = resultObj.getString("uuid");
            String mobilePhone = resultObj.getString("mobilePhone");
            //开立模拟账户接口
            AccountRequest.openDemo(mContext, uuid, mobilePhone, new ReqCallBack<DataItemDetail>() {
                @Override
                public void onReqSuccess(DataItemDetail itemDetail) {
                    loginAccount = itemDetail.getString("customerNumber");
                    loginPass = itemDetail.getString("password");
                    accAccountLogin(loginAccount, loginPass, GTConfig.ACC_TYPE_DEMO);
                }

                @Override
                public void onReqFailed(String errorMsg) {
                    onPhoneRequestFail(100);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析数据并根据逻辑执行登录或者弹窗
     */
    private void accLoginOrBind(String rgsUrl, final int accountType) {
        try {
            final JSONObject jsonRgsUrl = new JSONObject(rgsUrl);
            if (!jsonRgsUrl.isNull("result")) {
                JSONObject resultObj = jsonRgsUrl.getJSONObject("result");
                if (!resultObj.isNull("customerNumber") && !resultObj.isNull("demoCustomerNumber")) {//1.绑定了真实和模拟账号，直接登录
                    if (accountType == GTConfig.ACC_TYPE_DEMO) {
                        loginAccount = resultObj.getString("demoCustomerNumber");
                        loginPass = GTConfig.instance().mUserPwd;
                        mAccountType = GTConfig.ACC_TYPE_DEMO;
                    } else {
                        loginAccount = resultObj.getString("customerNumber");
                        loginPass = GTConfig.instance().mUserPwd;
                        mAccountType = GTConfig.ACC_TYPE_REAL;
                    }
                    if (GTConfig.FROM_QUOTE.equals(switchFrom)) {//行情页面直接切换
                        accAccountLogin(loginAccount, loginPass, mAccountType);
                    } else {//带提示弹窗的切换
                        showLoginDialog(loginAccount, loginPass, accountType);
                    }
                } else {//2.根据登录的账号是否绑定，判断切换的逻辑
                    if (accountType == GTConfig.ACC_TYPE_DEMO) {//2.1 切换到模拟
                        if (!resultObj.isNull("customerNumber") && resultObj.isNull("demoCustomerNumber")) {
                            accountOpenOrBind(jsonRgsUrl, GTConfig.ACC_TYPE_DEMO);
                        } else if (resultObj.isNull("customerNumber") && !resultObj.isNull("demoCustomerNumber")) {
                            //绑定真实账号，也就是现在登录账号
                            String bindName = GTConfig.instance().mCurName;
                            String loginName = resultObj.getString("demoCustomerNumber");
                            accountToBind2(loginName, bindName, accountType, GTConfig.ACC_TYPE_REAL);
                        } else {
                            accountOpenOrBind(jsonRgsUrl, accountType);
                        }
                    } else {//2.2 切换到真实
                        if (!resultObj.isNull("customerNumber") && resultObj.isNull("demoCustomerNumber")) {
                            //绑定模拟，也就是现在登录账号
                            final String bindName = GTConfig.instance().mCurName;
                            final String loginName = resultObj.getString("customerNumber");
                            accountToBind2(loginName, bindName, accountType, GTConfig.ACC_TYPE_DEMO);
                        } else if (resultObj.isNull("customerNumber") && !resultObj.isNull("demoCustomerNumber")) {
                            accountOpenOrBind(jsonRgsUrl, GTConfig.ACC_TYPE_REAL);//2.切换到真实
                        } else {
                            accountOpenOrBind(jsonRgsUrl, accountType);
                        }
                    }
                }
            } else {
                accountOpenOrBind(jsonRgsUrl, accountType);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void accountOpenOrBind(JSONObject jsonResult, final int accountType) {
        final DataItemResult ItemResult = GTDataResolve.getInstance().dealPhoneLoginData(jsonResult, accountType);
        if (accountType == GTConfig.ACC_TYPE_DEMO) {//切换到模拟
            if (ItemResult.getDataCount() < 1) {//行情页面切换到模拟，自动绑定
                if (!jsonResult.isNull("result")) {
                    openDemoAccount(jsonResult);
                } else {//result为null 真实没绑定手机，切换模拟，无法获取UUID,這時需要調用綁定接口將此時登錄的賬號綁定，才能獲取到uuid
                    final String bindAccount = GTConfig.instance().mCurName;
                    final String loginPass = GTConfig.instance().mUserPwd;
                    mSeq = GTSDataListener.curSeq++;
                    PhoneLoginPresenter.instance().BindCustomerFun(AppContances.NORMALREQ_TYPE_BINDCUSTOMER, mSeq, GTConfig.ACC_TYPE_REAL, bindAccount, loginPass, new PhoneLoginPresenter.OnMobileReqResultListener() {
                        @Override
                        public void reqResultSuccess(Object mObject) {
                            JSONObject result = (JSONObject) mObject;
                            if (null != result && !result.isNull("result")) {
                                openDemoAccount(result);
                            }
                        }

                        @Override
                        public void reqResultFail(int failCode) {
                            hideLoading();
                            onPhoneRequestFail(failCode);
                        }
                    });
                }
            } else {
                if (ItemResult.getDataCount() == 1) {
                    DataItemDetail mDetail = ItemResult.getItem(0);
                    if (mDetail.getBoolean("locked")) {
                        onPhoneRequestFail(7);
                    } else {
                        accountToBind(ItemResult, accountType);
                    }
                } else {
                    accountToBind(ItemResult, accountType);
                }

            }
        } else {//切换到真实账户
            if (ItemResult.getDataCount() < 1) {//行情页面切换到真实账号，提示填写注册资料
                if (!jsonResult.isNull("result")) {
                    hideLoading();
                    try {
                        JSONObject resultObj = jsonResult.getJSONObject("result");
                        String uuid = resultObj.getString("uuid");
                        String mobilePhone = resultObj.getString("mobilePhone");
                        AddAccountInfoDialog.showAddAccountInfoDialog(mContext, AppMain.getAppString(R.string.add_info_tips), uuid, mobilePhone);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {//模拟没绑定手机，切换真实，无法获取UUID
                    final String bindAccount = GTConfig.instance().mCurName;
                    final String loginPass = GTConfig.instance().mUserPwd;
                    mSeq = GTSDataListener.curSeq++;
                    PhoneLoginPresenter.instance().BindCustomerFun(AppContances.NORMALREQ_TYPE_BINDCUSTOMER, mSeq, GTConfig.ACC_TYPE_DEMO, bindAccount, loginPass, new PhoneLoginPresenter.OnMobileReqResultListener() {
                        @Override
                        public void reqResultSuccess(Object mObject) {
                            hideLoading();
                            JSONObject result = (JSONObject) mObject;
                            if (null != result && !result.isNull("result")) {
                                try {
                                    JSONObject resultObj = result.getJSONObject("result");
                                    String uuid = resultObj.getString("uuid");
                                    String mobilePhone = resultObj.getString("mobilePhone");
                                    AddAccountInfoDialog.showAddAccountInfoDialog(mContext, AppMain.getAppString(R.string.add_info_tips), uuid, mobilePhone);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                        @Override
                        public void reqResultFail(int failCode) {
                            hideLoading();
                            onPhoneRequestFail(failCode);
                        }
                    });
                }
            } else {
                if (ItemResult.getDataCount() == 1) {
                    DataItemDetail mDetail = ItemResult.getItem(0);
                    if (mDetail.getBoolean("locked")) {
                        onPhoneRequestFail(7);
                    } else {
                        accountToBind(ItemResult, accountType);
                    }
                } else {
                    accountToBind(ItemResult, accountType);
                }
            }
        }
    }

    /**
     * 1.登录的账号没绑定的，但是切换的账号是已经绑定的，这时候要弹窗绑定
     */
    private void accountToBind2(final String curName, String BindName, final int accountType, final int bindType) {
        hideLoading();

        mPresenter.accSwitchAccount2(curName, BindName, accountType, mContext,
                new BindEnterPasswordDialog.BtnConfirmListener() {
                    @Override
                    public void onBtnClick(DataItemDetail item, String mPassWord) {
                        showLoading();
                        accBindCustomer(curName, item, mPassWord, bindType, accountType);
                    }
                });
    }

    /**
     * 2.登录的账号是绑定的，但是切换的账号是没绑定的
     */
    private void accountToBind(DataItemResult ItemResult, final int accountType) {
        hideLoading();
        mPresenter.accSwitchAccount(GTConfig.instance().mCurName, ItemResult, false, accountType, mContext,
                new BindEnterPasswordDialog.BtnConfirmListener() {
                    @Override
                    public void onBtnClick(DataItemDetail item, String mPassWord) {
                        showLoading();
                        String loginAccount = item.getString("customerNumber");
                        accBindCustomer(loginAccount, item, mPassWord, accountType, accountType);
                    }
                });
    }


    /**
     * 显示加载圈
     */
    private void showLoading() {
        final BaseActivity mActivity = (BaseActivity) mContext;
        if (null != mActivity) {
            mActivity.showLoading();
        }
    }

    /**
     * 隐藏加载圈
     */
    private void hideLoading() {
        final BaseActivity mActivity = (BaseActivity) mContext;
        if (null != mActivity) {
            mActivity.hideLoading();
        }
    }

    /**
     * 提示模拟账户用户切换到真实
     */
    private void showLoginDialog(final String loginName, final String loginPass, final int accountType) {
        hideLoading();
        SwitchAccountDialog.showSwitchAccountDialog(mContext, ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1014)
                , new BtnClickListener() {
                    @Override
                    public void onBtnClick(int viewID) {
                        showLoading();
                        if (!StringUtils.isEmpty(loginName) && !StringUtils.isEmpty(loginPass)) {
                            accAccountLogin(loginName, loginPass, accountType);
                        }
                    }
                });
    }

    private void accAccountLogin(String loginName, String loginPass, int accountType) {
        mPresenter.mCurName = loginName;
        mPresenter.mPassword = loginPass;
        mPresenter.isLoading = true;
        mPresenter.isClickLogin = true;
        GTConfig.instance().setAccountType(accountType);
        mPresenter.setPresenterImpl(mPresenterImpl);
        DataManager.instance().reset();
        RxBus.getInstance().post(GTSConst.REPLY_SWITCH_ACCOUNT + "", true);
        mPresenter.loginFun();
    }


    private void onPhoneRequestFail(final int failCode) {

        final BaseActivity mActivity = (BaseActivity) mContext;
        if (null != mActivity) {
            mActivity.hideLoading();
            String error;
            if (failCode == 1) {
                error = AppMain.getAppString(R.string.account_isbinded);
            } else if (failCode == 7) {
                error = AppMain.getAppString(R.string.account_locked);
            } else if (failCode == 100) {//开立模拟账户失败
                error = AppMain.getAppString(R.string.open_demo_account_error);
            } else {
                error = ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1100) + "(" + failCode + ")";
            }
            PopupConfirmDialog dialog = PopupConfirmDialog.newInstance(mActivity, error);
            dialog.setCancelable(false);
            dialog.show();
            clearData();
        }
    }

    /**
     * 回收对象
     */
    public void clearData() {
        if (null != mPresenter) {
            mPresenter.isLoading = false;
            mPresenter.setPresenterImpl(null);
            mPresenter = null;
        }
        if (null != rxBusRegister && !rxBusRegister.isDisposed()) {
            rxBusRegister.dispose();
            rxBusRegister = null;
        }
        mContext = null;
    }
}
